﻿using IronPdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Spire.Pdf;
using Spire.Pdf.Annotations;
using Spire.Pdf.Annotations.Appearance;
using Spire.Pdf.ColorSpace;
using Spire.Pdf.Fields;
using Spire.Pdf.General.Find;
using Spire.Pdf.Graphics;
using Spire.Pdf.Security;
using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using PdfDocument = Spire.Pdf.PdfDocument;

namespace XZTZ.UMP.WEB.Pages.Change
{
    [IgnoreAntiforgeryToken(Order = 1001)]
    public class ShowTableModel : PageModel
    {
        public void OnGet()
        {

        }
        [BindProperty]
        public string TxtBaseUrl { get; set; }

        [BindProperty]
        public string TxtWidth { get; set; }

        [BindProperty]
        public string TxtHeight { get; set; }

        public IActionResult OnPostDown(string htmlCode)
        {
            #region 不支持
            //PdfDocument pdf = new PdfDocument();

            //PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat
            //{
            //    IsWaiting = false
            //};
            //PdfPageSettings setting = new PdfPageSettings
            //{
            //    Size = PdfPageSize.A4
            //};
            //Thread thread = new Thread(() =>
            //{
            //    pdf.LoadFromHTML("111", false, setting, htmlLayoutFormat);
            //});
            //thread.SetApartmentState(ApartmentState.STA);
            //thread.Start();
            //thread.Join();
            //MemoryStream memoryStream = new MemoryStream();
            //pdf.SaveToStream(memoryStream);
            //byte[] bytes = memoryStream.ToArray();
            //memoryStream.Close();
            //return File(bytes, "application/x-sh", "b.pdf");
            #endregion

            #region 方法1 select.htmltopdf
            //htmlCode = Regex.Replace(htmlCode, @"<script[^>]*?>[\s\S]*<\/script>", "", RegexOptions.IgnoreCase);

            //PdfPageSize pageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize),
            //    "A4", true);

            //PdfPageOrientation pdfOrientation =
            //    (PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation),
            //    "Portrait", true);

            //int webPageWidth = 1024;

            //try
            //{
            //    webPageWidth = Convert.ToInt32("1024");
            //}
            //catch { }

            //int webPageHeight = 0;

            //try
            //{
            //    webPageHeight = Convert.ToInt32(TxtHeight);
            //}
            //catch { }

            //HtmlToPdf converter = new HtmlToPdf();

            //converter.Options.PdfPageSize = pageSize;
            //converter.Options.PdfPageOrientation = pdfOrientation;
            //converter.Options.WebPageWidth = webPageWidth;
            //converter.Options.WebPageHeight = webPageHeight;

            //PdfDocument doc = converter.ConvertHtmlString(htmlCode, TxtBaseUrl);

            //byte[] pdf = doc.Save();

            //doc.Close();
            //FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            //fileResult.FileDownloadName = "Document.pdf";
            //return fileResult;
            #endregion

            #region 方法2
            htmlCode = Regex.Replace(htmlCode, @"<script[^>]*?>[\s\S]*<\/script>", "", RegexOptions.IgnoreCase);
            IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();

            Renderer.PrintOptions.SetCustomPaperSizeInInches(12.5, 20);
            Renderer.PrintOptions.PrintHtmlBackgrounds = true;
            Renderer.PrintOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Portrait;
            Renderer.PrintOptions.EnableJavaScript = true;
            Renderer.PrintOptions.RenderDelay = 50; //ms
            Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
            Renderer.PrintOptions.DPI = 300;
            Renderer.PrintOptions.FitToPaperWidth = true;
            Renderer.PrintOptions.JpegQuality = 80;
            Renderer.PrintOptions.GrayScale = false;
            Renderer.PrintOptions.FitToPaperWidth = true;
            Renderer.PrintOptions.InputEncoding = Encoding.UTF8;
            Renderer.PrintOptions.Zoom = 100;
            Renderer.PrintOptions.CreatePdfFormsFromHtml = true;
            Renderer.PrintOptions.MarginTop = 0;  //millimeters
            Renderer.PrintOptions.MarginLeft = 20;  //millimeters
            Renderer.PrintOptions.MarginRight = 20;  //millimeters
            Renderer.PrintOptions.MarginBottom = 0;  //millimeters
            Renderer.PrintOptions.FirstPageNumber = 1; //use 2 if a coverpage  will be appended

            // Render an HTML document or snippet as a string
            byte[] pdf = Renderer.RenderHtmlAsPdf(htmlCode).SaveAs("html-string.pdf").BinaryData;
            #endregion

            //从新加载文档由Spire.Pdf处理
            PdfDocument doc = new PdfDocument();
            doc.LoadFromBytes(pdf);

            #region 删除可能带有的水印
          
            PdfPageBase page = null;
            PdfAnnotationCollection widgetCollection = null;
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                page = doc.Pages[i];
                for (int j = 0; j < page.ImagesInfo.Length; j++)
                {
                    page.DeleteImage(j);
                }

                widgetCollection = page.AnnotationsWidget;
                for (int j = 0; j < page.AnnotationsWidget.Count; j++)
                {
                    widgetCollection.RemoveAt(j);
                }
            }

            #endregion

            //检索文字位置
            PdfTextFindCollection text = doc.Pages[doc.Pages.Count - 1].FindText("复核");
            float findx = 0;
            float findy = 0;
            findx = text.Finds[text.Finds.Length - 1].Position.X - 80;
            findy = text.Finds[text.Finds.Length - 1].Position.Y - 80;

            #region 加图章和签名
            //加载pfx证书
            PdfCertificate cert = new PdfCertificate(@"C:\Users\dell\Desktop\pfx\goodstudent.pfx", "lcf924115354");

            //添加数字签名到指定位置
            PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "signature");
            signature.Bounds = new RectangleF(new PointF(findx, findy), new SizeF(160, 160));

            //设置数字签名内容
            //signature.SignDetailsFont = new PdfTrueTypeFont(new Font("宋体", 10f, FontStyle.Regular), true);
            //signature.NameLabel = "签字人：廖成飞";
            //signature.LocationInfoLabel = "地点：";
            //signature.LocationInfo = "中国，重庆市";
            //signature.ReasonLabel = "原因： ";
            //signature.Reason = "证明文档有效性";
            //signature.DateLabel = "日期： ";
            //signature.Date = DateTime.Now;
            //signature.ContactInfoLabel = "联系电话： ";
            //signature.ContactInfo = "13888888888";

            //Bitmap img = new Bitmap(@"C:\Users\dell\Desktop\pfx\yz160.png");
            //Bitmap bb=img_alpha(img, 100);

            signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges;
            signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
            signature.SignImageSource = PdfImage.FromFile(@"C:\Users\dell\Desktop\pfx\yz160.png");

            //配置时间戳服务器
            //string url = "http://timestamp.wosign.com/rfc3161";
            //signature.ConfigureTimestamp(url);

            MemoryStream memoryStream = new MemoryStream();
            doc.SaveToStream(memoryStream);
            pdf = memoryStream.ToArray();
            memoryStream.Close();

            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
            #endregion
        }

        /// <summary>
        /// 图片透明度调节
        /// </summary>
        /// <param name="src">图片源</param>
        /// <param name="alpha">透明度0-255</param>
        /// <returns>返回透明图片</returns>
        public static Bitmap img_alpha(Bitmap src, int alpha)
        {
            Bitmap bmp = new Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            for (int h = 0; h < src.Height; h++)
            for (int w = 0; w < src.Width; w++)
            {
                Color c = src.GetPixel(w, h);
                bmp.SetPixel(w, h, Color.FromArgb(alpha, c.R, c.G, c.B));//色彩度最大为255，最小为0
            }
            return bmp;
        }
      
    }
}